package com.legendframework.core.cmd.paramer.converter.impl;

import com.legendframework.core.cmd.annotation.Size;
import com.legendframework.core.cmd.exception.ParameterCastException;
import com.legendframework.core.cmd.exception.ParameterLimitException;
import com.legendframework.core.cmd.paramer.converter.ParamerConverter;
import com.legendframework.core.ioc.IParameter;
import org.bukkit.command.CommandSender;

import java.lang.reflect.Field;
import java.lang.reflect.Parameter;

/**
 * 抽象的数值转换器
 * @param <T>
 */
public abstract class AbstractNumberTypeParamerConverter<T> implements ParamerConverter<T> {

    /**
     * 值转换
     * @param sender 发送者
     * @param message 消息
     * @param type 需要转换的类
     * @return
     */
    protected abstract T castValue(CommandSender sender, String message, Class<T> type , IParameter parameter);

    /**
     * 数值公共的类型转换
     */
    public T castParameter(CommandSender sender, String message, Class<T> type , IParameter parameter){
        T value = castValue(sender,message,type,parameter);
        Size size = parameter.getAnnotation(Size.class);
        if (size == null) {
            return value;
        }
        Number number = null;
        if (value instanceof Integer) {
            number = (Number) value;
        } else if (value instanceof Byte){
            number = (Number) value;
        } else if (value instanceof Short) {
            number = (Number) value;
        } else if (value instanceof Long) {
            number = (Long) value;
        } else if (value instanceof Float) {
            number = (Float) value;
        } else if (value instanceof Double) {
            number = (Double) value;
        }
        if (number == null) {
            throw new ParameterCastException("数值转换器没有找到合适的类型进行转换");
        }
        if (number.doubleValue() < size.min() || number.doubleValue() > size.max()) {
            throw new ParameterLimitException(size.message());
        }
        return value;
    }
}
